package com.develop.protocol;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.develop.vo.AlarmMsgVo;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import io.netty.util.ReferenceCountUtil;

public class AlarmDecoder extends LengthFieldBasedFrameDecoder {
	private static final Logger LOG = LoggerFactory.getLogger(AlarmDecoder.class);
	private static final int HEADER_SIZE = 9;
	@SuppressWarnings("unused")
	private short startSign;
	private byte msgType;
	private int timeStamp;
	private short lenOfBody;
	private String body;

	protected Object decode(ChannelHandlerContext ctx, ByteBuf byteBuf) throws Exception {
		ByteBuf in = (ByteBuf) super.decode(ctx, byteBuf);
		try {
			Object localObject1;
			if (in == null) {
				localObject1 = null;
				return localObject1;
			}
			ReferenceCountUtil.release(null);
			if (in.readableBytes() < HEADER_SIZE) {
				LOG.warn("可读信息段比头部信息都小!!!");
				in.clear();
				localObject1 = null;
				return localObject1;
			}
			this.startSign = in.readShort();

			this.msgType = in.readByte();

			this.timeStamp = in.readInt();

			this.lenOfBody = in.readShort();

			if (in.readableBytes() < this.lenOfBody) {
				LOG.info("body字段你告诉我长度是" + this.lenOfBody + ",实际长度不足！！！");
				localObject1 = null;
				return localObject1;
			}
			if (this.lenOfBody < 0) {
				LOG.info("消息体长度为负数");
				localObject1 = null;
				return localObject1;
			}
			ByteBuf buf = in.readBytes(this.lenOfBody);

			byte[] bts = new byte[buf.readableBytes()];

			buf.readBytes(bts);

			this.body = new String(bts);

			AlarmMsgVo alarmMsgVo = new AlarmMsgVo(this.msgType, this.timeStamp, this.lenOfBody, this.body);
			AlarmMsgVo localMsgVo1 = alarmMsgVo;
			return localMsgVo1;
		} finally {
			if (in != null)
				in.release();
		}
	}

	public AlarmDecoder(int maxFrameLength, int lengthFieldOffset, int lengthFieldLength, int lengthAdjustment, int initialBytesToStrip, boolean failFast) {
		super(maxFrameLength, lengthFieldOffset, lengthFieldLength, lengthAdjustment, initialBytesToStrip, failFast);
	}
}